import * as svg from '@element-plus/icons-vue';
import setIntroduction from '/@/utils/setIconfont';

// 类型定义
interface StyleSheet {
	href?: string;
	cssRules?: CSSRuleList;
}

interface CSSRule {
	selectorText?: string;
}

// 通用CSS解析函数
const parseIconsFromStyleSheets = (
	pattern: RegExp,
	identifier?: string
): Promise<string[]> => {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			const styles = document.styleSheets as unknown as StyleSheet[];
			const sheetsIconList: string[] = [];

			for (let i = 0; i < styles.length; i++) {
				try {
					const stylesheet = styles[i];

					// 如果有特定标识符，检查是否匹配
					if (identifier && stylesheet.href) {
						if (!stylesheet.href.includes(identifier)) {
							continue;
						}
					}

					if (stylesheet.cssRules) {
						for (let j = 0; j < stylesheet.cssRules.length; j++) {
							const rule = stylesheet.cssRules[j] as CSSRule;
							if (rule.selectorText && pattern.test(rule.selectorText)) {
								const cleanSelector = rule.selectorText
									.substring(1, rule.selectorText.length)
									.replace(/::before/gi, '');

								if (!sheetsIconList.includes(cleanSelector)) {
									sheetsIconList.push(cleanSelector);
								}
							}
						}
					}
				} catch (error) {
					console.warn(`无法访问样式表 ${i}:`, styles[i]?.href, error);
				}
			}
			if (sheetsIconList.length > 0) {
				resolve(sheetsIconList.sort());
			} else {
				const message = identifier
					? `未获取到${identifier}图标，请检查图标库是否正确加载`
					: '未获取到图标，请刷新重试';
				reject(new Error(message));
			}
		});
	});
};

// 获取阿里字体图标 (原有的 wtm 图标库)
const getAlicdnIconfont = (): Promise<string[]> => {
	return parseIconsFromStyleSheets(/\._wtmicon-[^:,\s]+::before/, 'WTM');
};

// 获取iconfont字体图标库 - 使用本地JSON数据
const getCustomAliIconfont = (): Promise<string[]> => {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			try {
				// 直接从本地JSON数据获取图标列表
				const iconList = setIntroduction.getIconList();
				if (iconList && iconList.length > 0) {
					console.log('从本地JSON获取到图标数量:', iconList.length);
					resolve(iconList.sort());
				} else {
					reject(new Error('未获取到本地iconfont图标数据'));
				}
			} catch (error) {
				console.error('获取本地iconfont图标失败:', error);
				// 降级到CSS解析方式
				console.log('尝试从CSS样式表解析图标...');
				parseIconsFromStyleSheets(/\.icon-[^:,\s]+::before/, 'font_4970436')
					.then(resolve)
					.catch(reject);
			}
		});
	});
};

// 初始化获取 css 样式，获取 element plus 自带 svg 图标，增加了 ele- 前缀
const getElementPlusIconfont = (): Promise<string[]> => {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			try {
				const icons = svg as Record<string, { name: string }>;
				const sheetsIconList: string[] = [];

				for (const iconName in icons) {
					if (icons[iconName]?.name) {
						sheetsIconList.push(`ele-${icons[iconName].name}`);
					}
				}
				if (sheetsIconList.length > 0) {
					resolve(sheetsIconList.sort());
				} else {
					reject(new Error('未获取到Element Plus图标'));
				}
			} catch (error) {
				console.error('获取Element Plus图标失败:', error);
				reject(error);
			}
		});
	});
};

// 初始化获取 css 样式，这里使用 fontawesome 的图标
const getAwesomeIconfont = (): Promise<string[]> => {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			const styles = document.styleSheets as unknown as StyleSheet[];
			const sheetsIconList: string[] = [];
			let foundLibrary = false;
			for (let i = 0; i < styles.length; i++) {
				try {
					const stylesheet = styles[i];

					// 检查是否是FontAwesome样式表
					if (stylesheet.href &&
						(stylesheet.href.includes('font-awesome') ||
							stylesheet.href.includes('fontawesome'))) {
						foundLibrary = true;
					}

					if (stylesheet.cssRules) {
						for (let j = 0; j < stylesheet.cssRules.length; j++) {
							const rule = stylesheet.cssRules[j] as CSSRule;
							if (rule.selectorText &&
								rule.selectorText.startsWith('.fa-') &&
								rule.selectorText.includes('::before') &&
								!rule.selectorText.includes(',')) {

								const cleanSelector = rule.selectorText
									.substring(1, rule.selectorText.length)
									.replace(/::before/gi, '');

								if (!sheetsIconList.includes(cleanSelector)) {
									sheetsIconList.push(cleanSelector);
								}
							}
						}
					}
				} catch (error) {
					console.warn(`无法访问样式表 ${i}:`, styles[i]?.href, error);
				}
			}
			if (sheetsIconList.length > 0) {
				resolve(sheetsIconList.sort().reverse());
			} else {
				const message = foundLibrary
					? '找到FontAwesome图标库但未解析到图标'
					: '未找到FontAwesome图标库，请检查是否正确加载';
				reject(new Error(message));
			}
		});
	});
};

/**
 * 获取字体图标 `document.styleSheets`
 * @method ali 获取阿里字体图标 (原有wtm) `<i class="_wtmicon 图标类名"></i>`
 * @method custom 获取iconfont阿里字体图标 `<i class="iconfont 图标类名"></i>`
 * @method ele 获取 element plus 自带图标 `<i class="图标类名"></i>`
 * @method awe 获取 fontawesome 的图标 `<i class="fa 图标类名"></i>`
 */
const initIconfont = {
	// iconfont (原有)
	ali: getAlicdnIconfont,
	// iconfont阿里图标库
	custom: getCustomAliIconfont,
	// element plus
	ele: getElementPlusIconfont,
	// fontawesome
	awe: getAwesomeIconfont,
} as const;

// 导出方法
export default initIconfont;
